$(function () {
    findById();
})

/**
 * 查询id
 */
function findById() {
    let id = sessionStorage.getItem("userId");
    let result = myAjax("/admin/user/findById", {id: id}, "post");
    console.log(result);
    if (result != null) {
        setData(result.model);
    }
}

//赋值
function setData(data) {
    $("#username").val(data.userName);
    $("#phone").val(data.phone);
    $("#email").val(data.email);
    $("#age").val(data.age);
    $("input[name='sex'][value=" + data.sex + "]").attr("checked", true);
    $("#birthday").val(data.birthday);
    setHobby(data.hobby);
}

function setHobby(data) {
    //将从数据库拿到的数据中的[]和空格置换为空
    let hobby = data.replace("[", "").replace("]", "").replace(" ", "").replace("，", ",");
    //将字符串转换为数组
    let hobbys = hobby.split(",");
    //遍历数组
    $('input:checkbox[name="hobby"]').each(function () {
        for (let i = 0; i < hobbys.length; i++) {
            if ($(this).val() == hobbys[i]) {
                //当数据库中的数据与前端页面的复选框value相等时即为选中
                $("input:checkbox[value=" + hobbys[i] + "]").attr('checked', true);
            }
        }
    });
}

//提交表单时再一次判断提交数据是否正确
function save() {
    let data = {
        id: sessionStorage.getItem("userId"),
        userName: $("#username").val(),
        phone: $("#phone").val(),
        email: $("#email").val(),
        sex: $('input:radio[name="sex"]:checked').val(),
        age: $("#age").val(),
        birthday: $("#birthday").val(),
        hobby: getHobby().toLocaleString(),
    };
    console.log(data);
    //连接后台servlet
    let result = myAjax("/admin/user/edit", data, "post");
    console.log(result);
    if (result.result == "success") {
        alert("修改成功(=^ ^=)！");
        window.location.reload();
    } else if (result.result == "isHave") {
        alert("当前用户名火爆，请另取一个哟亲(=^ ^=)！")
    } else {
        alert("修改失败，请重新输入！");
    }
}

function getHobby() {
    let hobby = [];
    $("input:checkbox[name=hobby]").each(function () {
        if ($(this).prop('checked')) {
            hobby.push($(this).val());
        }
    })
    return hobby;
}

// function goBack() {
//     window.open("/step-seven-admin/propertyHtml/user-manage.html","_self");
// }

